package com.xy.deepclone;

import sun.nio.cs.ext.IBM037;

import java.io.*;

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2022/6/10 15:52
 * @description
 */
public class DeepPrototype implements Serializable, Cloneable{

    private static final long serialVersionUID = 1L;

    public String name;

    public DeepCloneableTarget deepCloneableTarget;

    public DeepPrototype() {

    }

    /**
     * 深拷贝方式一 使用clone
     *
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected DeepPrototype clone() throws CloneNotSupportedException {
        DeepPrototype deep = null;
        deep = (DeepPrototype) super.clone();
        deep.deepCloneableTarget = deepCloneableTarget.clone();
        return deep;
    }

    /**
     * 通过对象序列化实现深拷贝 (推荐使用)
     */
    public DeepPrototype deepClone() {

        // 序列化
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {

            // 写出数据
            oos.writeObject(this);

            // 反序列化
            try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                 ObjectInputStream ois = new ObjectInputStream(bis)) {
                return (DeepPrototype) ois.readObject();
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    @Override
    public String toString() {
        return "DeepPrototype{" +
                "name='" + name + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }
}
